<script setup>
	import { ref, reactive } from "vue"
	import { gotoHome } from "@/utils/common.js"
	import { getClassifyListAPI, getHistoryListAPI } from "@/api/classify.js"
	import { onLoad, onUnload, onReachBottom, onShareAppMessage, onShareTimeline } from "@dcloudio/uni-app"

	// 请求参数
	const queryParams = reactive({ pageNum: 1, pageSize: 12 })
	// 获取列表
	const isFinally = ref(false)
	const isLoading = ref(false)
	const classifyList = ref([])
	const getClassifyList = async () => {
		try {
			isLoading.value = true
			const res = queryParams.type ? await getHistoryListAPI(queryParams) : await getClassifyListAPI(queryParams)
			classifyList.value.push(...res.data)
			// 是否还有数据
			if (classifyList.value.length < res.total) {
				queryParams.pageNum++
			} else {
				isFinally.value = true
			}
		} finally {
			isLoading.value = false
		}
	}

	// 查看详情
	const onPreview = (id) => {
		// 设置缓存
		uni.setStorageSync("classifyList", classifyList.value)
		uni.navigateTo({ url: `/pages/preview/preview?id=${id}` })
	}

	// 页面加载
	const navBarTitle = ref("")
	onLoad((options) => {
		// 我的评分|我的下载
		if (options.type) queryParams.type = options.type
		// 壁纸分类
		if (options.id) queryParams.classid = options.id

		// if (!options.id) return gotoHome()
		navBarTitle.value = options.name
		// 修改标题
		uni.setNavigationBarTitle({ title: options.name })
		getClassifyList()
	})
	// 页面触底
	onReachBottom(() => {
		if (isLoading.vlaue) return
		if (isFinally.value) return
		getClassifyList()
	})

	// 分享好友
	onShareAppMessage((e) => {
		return {
			title: `拾光壁纸-${navBarTitle.value}`,
			path: `/pages/classify-list/classify-list?id=${queryParams.classid}&name=${navBarTitle.value}`
		}
	})
	// 分享朋友圈
	onShareTimeline(() => {
		return {
			title: `拾光壁纸-${navBarTitle.value}`,
			query: `id=${queryParams.classid}&name=${navBarTitle.value}`
		}
	})

	// 离开页面
	onUnload(() => {
		uni.removeStorageSync("classifyList")
	})
</script>

<template>
	<!-- 加载状态 -->
	<view class="loading-box" v-if="!classifyList.length && !isFinally">
		<uni-load-more status="loading"></uni-load-more>
	</view>
	<view class="classify-list">
		<view class="item" v-for="item in classifyList" :key="item._id" @click="onPreview(item._id)">
			<image :src="item.smallPicurl" mode="aspectFill"></image>
		</view>
	</view>
	<!-- 触底加载 -->
	<view class="loading-box" v-show="(isLoading && classifyList.length) || isFinally">
		<uni-load-more :status="isFinally?'noMore':'loading'"></uni-load-more>
	</view>
	<view class="safe-area-inset-bottom"></view>
</template>

<style lang="scss" scoped>
	.classify-list {
		display: grid;
		grid-template-columns: repeat(3, 1fr);
		gap: 5rpx;
		padding: 5rpx;

		.item {
			height: 440rpx;

			image {
				width: 100%;
				height: 100%;
				display: block;
			}
		}
	}
</style>